/*
 * @Author: 王雁鹏
 * @Date: 2023-06-18 21:52:55
 * @LastEditTime: 2023-08-01 17:05:46
 * @LastEditors: Please set LastEditors
 * @Description: 
 * @FilePath: \expressf:\web-vue\bs-nodejs-background-code\routes\wechat\service.js
 * -------------------------------------
 */
const express = require('express');
const request = require('request')
var req = require("../../utils/router");
const db = require("../../mysql/index.js");
const { generateUUID, createToken } = require("../../utils/func.js")
let { router, GetRouter, PostRouter } = req
var WXBizDataCrypt = require('./WXBizDataCrypt')

// const wechat = require('wechat');
// const appId = 'wx7045c6b2645a9707';
// const appSecret = 'bdd7d21bde0e536b50c9f749839a4769';

// router.get('/wechat', wechat(appId, appSecret), (req, res) => {
//     // 处理微信服务器发来的请求  
//     const userInfo = req.weixin.user;
//     const token = generateToken(userInfo);
//     res.json({ token });
// })


var AppID = 'wxf8b267cff4c3bd83';
var AppSecret = '661b8f3dae3252f7e746f876bba6d94f';


// router.get('/wechat_login', function (req, res, next) {
//     // 第一步：用户同意授权，获取code
//     var router = 'get_wx_access_token';
//     // 这是编码后的地址  这里要修改成你本地的域名
//     var return_uri = 'http://162.14.64.133:8183/' + router;
//     var scope = 'snsapi_userinfo';
//     res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + AppID + '&redirect_uri=' + return_uri + '&response_type=code&scope=' + scope + '&state=STATE#wechat_redirect');

// });

new PostRouter().send('/get_wx_access_token', function (res, data) {
    console.log(data, "loginDataData")
    // 第二步：通过code换取网页授权access_token
    var code = data.code;
    request.get(
        {
            url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + AppID + '&secret=' + AppSecret + '&js_code=' + code + '&grant_type=authorization_code',
        },
        function (error, response, body) {
            if (response.statusCode == 200) {
                // 第三步：拉取用户信息(需scope为 snsapi_userinfo)
                var params = JSON.parse(body);
                let iv = decodeURIComponent(data.iv)
                let encryptedData = decodeURIComponent(data.encryptedData)
                console.log(encryptedData, params, "paramsparamsparams")

                let obj = {
                    id: db.EQ({
                        db: "wh_users",
                        select: {
                            openid: params.openid
                        }
                    }),
                }
                let select = db.Params(obj)
                db.select({
                    db: 'wh_users',
                    select
                }, (rows) => {
                    if (rows.list.length > 0) {
                        let { score, id, phone } = rows.list[0]
                        // let condition = { phone: phone }
                        // db.setData({
                        //     db: 'wh_users',
                        //     id,
                        //     condition
                        // }, (rows, fields) => {
                        // })
                        res.send({ data: { phoneNumber: phone, appid: AppID, openid: params.openid, score } });
                    } else {
                        var pc = new WXBizDataCrypt(AppID, params.session_key)
                        var dataObj = pc.decryptData(encryptedData, iv)
                        let score = 0
                        let openid = params.openid
                        let phone = dataObj.phoneNumber
                        let condition = {
                            openid,
                            phone,
                            score
                        }
                        console.log(condition, "condition")
                        db.setData({
                            db: 'wh_users',
                            condition
                        }, (rows, fields) => {
                        })
                        res.send({ data: { phoneNumber: dataObj.phoneNumber, appid: AppID, openid: params.openid, score } });
                    }
                })
            } else {
                res.send({ code: 100, msg: "登录失败！" })
            }
        }
    )
    // request.get({
    //     url: 'https://api.weixin.qq.com/cgi-bin/token?appid=' + AppID + '&secret=' + AppSecret + '&js_code=' + code + '&grant_type=client_credential'
    // },
    //     (error, response, body) => {
    //         var data = JSON.parse(body);
    //         let access_token = data.access_token

    //     })

})

new PostRouter().send('/userInfo', (res, data) => {
    let openid = data.openid
    console.log(openid)
    let obj = {
        id: db.EQ({
            db: "wh_users",
            select: {
                openid
            }
        }),
    }
    let select = db.Params(obj)
    db.select({
        db: 'wh_users',
        select
    }, (rows) => {
        console.log(rows)
        res.send({ code: 200, data: { ...rows.list[0] } });
    })
})


module.exports = router